// userPackage/pages/orderDetail/orderDetail.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    order: ''
  },

  toPage(e) {
    console.log(e);
    var flag = e.currentTarget.dataset.flag,
      order = this.data.order;
    if (flag == 'submit') {
      var arr = []
      order.orderInfoList.forEach(item => {
        arr.push({
          productImage: item.productImage,
          productName: item.productName,
          productKind: order.orderFlag == 1 ? 1 : 0,
          selectFormat: {
            factoryId: item.factoryId,
            formatId: item.formatId,
            formatName: item.formatName,
            productId: item.productId,
            selectNum: item.productNum,
            totalMoney: item.productTotal,
            productPrice: item.productPrice,
            productScore: item.productScore,
          }
        })
      })
      wx.navigateTo({
        url: '/orderPackage/pages/submitOrder/submitOrder?order=' + JSON.stringify(arr),
      })

    } else if (flag == 'pay') {
      // 立即支付
      this.payHandle(order)
    } else if (flag == 'cancel') {
      // 取消订单
      console.log(order);
      this.cancelOrConfirmOrderHandle(order.orderId, 4)
    } else if (flag == 'wuLiu') {
      // 查看物流
      console.log(order);
      wx.navigateTo({
        url: '/userPackage/pages/orderWuLiu/orderWuLiu?orderNum=' + order.orderNumber,
      })

    } else if (flag == 'shouhuo') {
      // 确认收货
      this.cancelOrConfirmOrderHandle(order.orderId, 3)
    } else if (flag == 'pingjia') {
      // 去评价

      var obj = e.currentTarget.dataset.obj;
      console.log(obj);
      // return
      wx.navigateTo({
        url: '/mainPackage/pages/evaluate/evaluate?id=' + obj.productId + '&orderNum=' + obj.orderNumber,
      })

    } else if (flag == 'del') {
      // 删除订单
      this.cancelOrConfirmOrderHandle(obj.orderId, 4)
    } else if (flag == 'returnGoods') {
      var obj = e.currentTarget.dataset.obj;
      console.log(obj);
      console.log(this.data.order);
      obj.orderTotalMoney = this.data.order.realMoney

      wx.navigateTo({
        url: '/orderPackage/pages/returnGoods/returnGoods?order=' + JSON.stringify(obj) + '&flag=1',
      })
    }
  },

  // 取消订单 确认收货
  cancelOrConfirmOrderHandle(orderId, status) {
    var url = app.globalData.url + "ScOrder/cancelOrder";
    wx.showModal({
      title: '提示',
      content: status == 4 ? '是否操作该订单' : '是否确认收货',
      complete: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '',
          })
          app.wxRequest(url, {
              orderId,
              status
            }, res => {
              console.log(res);
              if (res.flag) {
                wx.hideLoading()
                wx.showModal({
                  title: '提示',
                  content: '操作成功',
                  showCancel: false,
                  complete: (res) => {
                    if (res.confirm) {
                      wx.redirectTo({
                        url: '/userPackage/pages/order/order?index=' + status,
                      })
                    }
                  }
                })

              }
            },
            err => {
              console.log(err);
            })
        }
      }
    })



  },
  copyHandle(e) {
    var text = e.currentTarget.dataset.text;
    wx.setClipboardData({
      data: text,
      success: function (res) {
        wx.showToast({
          title: '复制成功',
          icon: "none",
          mask: "true"
        })
      }
    })
  },

  computedPoints(orderList, user, totalPoints) {

    orderList.forEach(item => {
      debugger
      var len = orderList.length;
      var residue = 0; //剩余积分
      var usedTotal = 0;
      if (index == len - 1) {
        residue = user.userBalance - usedTotal;
        item.deductScore = residue;
      } else {
        var rebate = item.productScore * item.productNum;
        item.deductScore = Math.ceil(user.userBalance * rebate / totalPoints);
        console.log(item.deductScore);
        usedTotal += item.deductScore;
      }
    })
    var order = this.data.order;
    order.orderInfoList = orderList;
    this.setData({
      order
    })



  },
  computedMoney(orderList, user, totalMoney) {
    orderList.forEach((item, index) => {
      var len = orderList.length;
      var residue = 0; //剩余积分
      var usedTotal = 0;
      if (index == len - 1) {
        residue = user.userBalance - usedTotal;
        item.deductMoney = residue;
      } else {
        var reta = item.productTotal / totalMoney;
        item.deductMoney = Math.ceil(user.userBalance * reta);
        usedTotal += item.deductMoney;
      }
    })
    var order = this.data.order;
    order.orderInfoList = orderList;
    this.setData({
      order
    })
  },



  // 支付
  payHandle(order) {
    var url = "",
      that = this;
    // wx.showLoading({
    //   title: '',
    // })
    console.log(order);
    console.log(app.globalData.user);
    var user = app.globalData.user;
    if (order.deductSource > user.userScore || order.usedBalance > user.userBalance) {
      wx.showModal({
        title: '提示',
        content: '当前账户余额或积分发生变化，支付金额发发生变化，确认提交订单',
        complete: (res) => {
          if (res.confirm) {


            order.deductSource = user.userScore;
            order.usedBalance = user.userBalance;
            order.realMoney = order.totalMoney - order.usedBalance;
            //  前往订单页
            var orderList = order.orderInfoList;
            var totalPoints = 0,
              totalMoney = 0;
            orderList.forEach(item => {
              item.deductMoney = 0;
              item.deductScore = 0;
              totalPoints += item.productScore * item.productNum;
              totalMoney += item.productPrice * item.productNum
            })
            order.orderInfoList = orderList;
            this.setData({
              order
            })
            if (order.deductSource > user.userScore) {
              if (user.userScore > 0) {
                this.computedPoints(orderList, user, totalPoints);
              }
            }
            if (order.usedBalance > user.userBalance) {
              if (user.userBalance > 0) {
                this.computedMoney(orderList, user, totalMoney);
              }
            }
            url = app.globalData.url + "ScOrder/updateOrder";
            var that = this;
            app.wxRequestJson(url, order, res => {
              console.log(res);
              that.toPay(order.realMoney, order.orderNumber);
            }, err => {
              console.log(err);
            })
          }
        }
      })

    } else {
      this.toPay(order.realMoney, order.orderNumber);
    }


  },
  toPay(realMoney, orderNumber) {
    var url = app.globalData.url + "pay/wxPay";
    app.wxRequest(url, {
        openId: app.globalData.openId,
        userId: app.globalData.userId,
        totalMoney: realMoney,
        orderNum: orderNumber,

      }, res => {
        console.log(res);
        if (res.flag) {

          wx.showModal({
            title: '提示',
            content: '支付成功',
            showCancel: false,
            confirmText: '立即查看',
            complete: (res) => {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/userPackage/pages/order/order?index=' + 1,
                })
              }
            }
          })
          return

          var datas = res.data.finalPackage;
          console.log(datas);
          wx.requestPayment({
            "timeStamp": datas.timeStamp,
            "nonceStr": datas.nonceStr,
            "package": datas.package,
            "signType": "RSA",
            "paySign": datas.paySign,
            "success": function (res) {
              console.log(res);
              if (res.errMsg == "requestPayment:ok") {
                //支付成功
                wx.showModal({
                  title: '提示',
                  content: '立即查看',
                  showCancel: false,
                  complete: (res) => {
                    if (res.confirm) {
                      //  前往订单页
                      wx.redirectTo({
                        url: '/userPackage/pages/order/order?index=' + 1,
                      })
                    }
                  }
                })
              }
            },
            "fail": function (res) {
              console.log(res);
              wx.showToast({
                title: '支付失败,请重试',
                icon: 'none'
              })
            },
            "complete": function (res) {
              console.log(res);
            }
          })

        } else {
          wx.showToast({
            title: res.message,
            icon: 'none'
          })
        }
      },
      err => {
        console.log(err);
      })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options);
    this.setData({
      order: JSON.parse(options.order)
    })
    console.log(this.data);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})